import React, {useState, useEffect} from 'react';
import { message, Tree, Spin } from 'antd';
import { getAllPermission, getCurrentPermission } from '../service';

interface PermissionProps {
  edit:boolean;
  param:number;
  checkedKeysList:[];
  disabled:boolean;
  selectChange: (values:any) => void;
}
/**
 * 
 * 所属机构控件
 */
const PermissionComponent: React.FC<PermissionProps> = (props) => {

  const { edit, param, checkedKeysList,disabled,selectChange } = props;
  const [loading, setLoading] = useState<boolean>(false);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);//默认展开节点
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);//默认选中节点
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);//选中的值
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [checkable, setCheckable] = useState<boolean>(true);
  const [treeData, setTreeData] = useState<any>();
  
  useEffect(() => {
    setTreeData([]);
    if(param){
      setLoading(true)
      if(edit){//添加/编辑
        new Promise((resolve, reject) => {
          getCurrentPermission(param)
            .then((res) => {
              if (res && res.code === 200) {
                setCheckable(true);
                const data = res.data;
                setTreeData(data);
                const expandedKeysList = [];
                for(let i in data){
                  expandedKeysList.push(data[i].key);
                }
                setExpandedKeys(expandedKeysList);
                resolve(true);
              } else {
                message.error('请求失败');
                resolve(false);
              }
              setTimeout(function(){setLoading(false);},200);
            })
            .catch((error) => {
              message.error('请求失败');
              reject(error);
            });
        });
      }else{//查看
        new Promise((resolve, reject) => {
          getAllPermission(param)
            .then((res) => {
              if (res && res.code === 200) {
                setCheckable(false);
                const data = res.data;
                setTreeData(data);
                const expandedKeysList = [];
                for(let i in data){
                  expandedKeysList.push(data[i].key);
                }
                setExpandedKeys(expandedKeysList);
                resolve(true);
              } else {
                message.error('请求失败');
                resolve(false);
              }
              setTimeout(function(){setLoading(false);},200);
            })
            .catch((error) => {
              message.error('请求失败');
              reject(error);
            });
        });
      }
    }
  },[param]);

  useEffect(() => {
    setCheckedKeys(checkedKeysList?.filter(item => item !=100000?item%10000:item).map(String)); //首页100000
  },[checkedKeysList]);

  const onExpand = expandedKeys => {
    console.log('onExpand', expandedKeys);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeys1,info) => {
    console.log('onCheck');
    console.log(checkedKeys1)
    console.log(info.halfCheckedKeys);
    const halfCheckedKeys = info.halfCheckedKeys;
    console.log([...checkedKeys1, ...halfCheckedKeys])
    // setCheckedKeys([...checkedKeys1, ...halfCheckedKeys]);
    setCheckedKeys(checkedKeys1)
    // form.setFieldsValue({"permissionId":checkedKeys?.toString()});
    selectChange([...checkedKeys1, ...halfCheckedKeys].map(Number));
  };

  const onSelect = (selectedKeys) => {
    console.log("onSelect");
    setSelectedKeys(selectedKeys);
  };

  return (
    <Spin spinning={loading}>
      <Tree
        disabled={disabled}
        checkable={checkable}
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        onSelect={onSelect}
        selectedKeys={selectedKeys}
        treeData={treeData}
      />
    </Spin>
  );
};

export default PermissionComponent;
